package src

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case


packageName = "" // 基础包名 根据所选择的文件夹自动转换
entityPackageName = "com.alpaca.module.common.entity" // 实体类所在包的路径
packageParentName = "" //基础包名的上一级包名
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def baseName = javaName(table.getName(), true, true)
    packageName = getPackageName(dir)
    packageParentName = getPackageParentName(packageName)
    // 创建mapper接口
    new File(dir, baseName + "Mapper.java").withPrintWriter("utf-8") { out -> generateFile(out, baseName) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

// 创建mapper接口
def generateFile(out, baseName) {
    out.println "package $packageName"
    out.println ""
    out.println "import org.apache.ibatis.annotations.Mapper;"
    out.println "import ${packageParentName}.entity.${baseName};"
    out.println "import com.baomidou.mybatisplus.core.mapper.BaseMapper;"
    out.println ""
    out.println "/**"
    out.println " *"
    out.println " * @author lzp" // 可自定义
    out.println " */"
    out.println "@Mapper"
    out.println "public interface ${baseName}Mapper extends BaseMapper<${baseName}>  {"
    out.println ""
    out.println "}"
}


/**
 *
 * @param str
 * @param capitalize 是否需要开头大写
 * @param needRemovePrefix 是否需要去掉前缀
 * @return
 */
def javaName(str, capitalize, needRemovePrefix) {
    if (needRemovePrefix) {
        def index = str.indexOf("_")
        if (index != null) {
            str = str.substring(str.indexOf("_") + 1)
        }
    }
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

/**
 * 获取包路径的上一级路径
 * @param path
 * @return
 */
def getPackageParentName(path) {
    def index = path.lastIndexOf(".")
    if (index != -1) {
        path = path.substring(0,index)
    }
}
